<template>
	<view class="full box relative bg-primary order-detail-container">
		<scroll-view class="full" scroll-y>
			<view class="order-status-bar" v-if="status === 1">
				<text class="title">未付款</text>
				<text class="desc">{{ endTimeStr }}</text>
			</view>
			<view class="order-status-bar" v-if="status === 5">
				<text class="title">订单已取消</text>
			</view>
			<view class="order-info-wrap">
				<view class="order-info">
					<view class="text-desc">
						<view class="text-title">
							<text>{{ lineName }}</text>
						</view>
						<view class="order-desc-list">
							<view class="order-desc-item">
								<text>{{ lineDesc }}</text>
							</view>
							<view class="order-desc-item" v-for="(item,index) in hotelData" :key="index">
								<text class="hotel-name-text">{{ item.hotelName }}:</text>
								<text class="hotel-type-item" v-for="(typeItem,typeIndedx) in item.children"
									:key="typeIndex">{{ typeItem.name }}x{{ typeItem.number }}</text>
							</view>
							<view class="order-desc-item">
								<text>成人X{{ adultNum }}，儿童X{{ childNum }}，老人X{{ oldNum }}</text>
							</view>
						</view>
					</view>
					<view class="order-image">
						<image :src="lineImage" class="full" mode="aspectFill"></image>
					</view>
				</view>
				<view class="line"></view>
				<view class="tip-list">
					<view class="tip-item">
						<text>1、本产品需二次预约，建议提前联系客服，本产品需二次预约，建议提前联系客服。</text>
					</view>
					<view class="tip-item">
						<text>2、法定节假日及前一天入住需补差价，详情请咨询客服。</text>
					</view>
				</view>
			</view>
			<view class="buy-info-wrap">
				<view class="header">
					<text>购买信息</text>
				</view>
				<view class="info-line"></view>
				<view class="info-list-wrap">
					<view class="info-item">
						<text class="info-label">联系人:</text>
						<text class="info-value">{{ userName }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">联系手机:</text>
						<text class="info-value">{{ userPhone }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">订单留言:</text>
						<text class="info-value">{{ userRemark || '无' }}</text>
					</view>
				</view>
			</view>
			<view class="buy-info-wrap">
				<view class="header">
					<text>订单信息</text>
				</view>
				<view class="info-line"></view>
				<view class="info-list-wrap">
					<view class="info-item">
						<text class="info-label">订单编号：{{ orderNo }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">下单时间：{{ createTime }}</text>
					</view>
					<view class="info-item" v-if="status > 1">
						<text class="info-label">支付时间：{{ payTime }}</text>
					</view>
				</view>
			</view>
			<view class="footer-wrap">
				<view class="btn-item service" @click="popupHandle(true)">
					<text>联系客服</text>
				</view>
				<template v-if="status === 1">
					<view class="btn-item" @click="cancelOrder">
						<text>取消订单</text>
					</view>
					<view class="btn-item confirm" @click="payOrder">
						<text>立即支付</text>
					</view>
				</template>
				<template v-if="status === 2">
					<view class="btn-item" @click="closeOrder">
						<text>申请退款</text>
					</view>
					<view class="btn-item confirm" @click="confirmOrder">
						<text>完成订单</text>
					</view>
				</template>
			</view>
		</scroll-view>
		<view class="absolute">
			<u-loading-page :loading="loading" />
			<service-popup :show="showPopup" @close="popupHandle(false)" />
		</view>
	</view>
</template>

<script>
	import ServicePopup from '@/pages/user/com/service.vue'
	import { mpWxPay, wxPerPay } from '../order-util/index.js'
	import { UPDATE_ORDER_FLAG } from '@/constant/index.js'
	let timerID = null
	export default {
		destroyed() {
			this.inPage = false

			console.log('页面销毁');
		},
		onLoad(ev) {
			// return this.createInterval('2023-09-07 14:04:50')
			if (!ev.hasOwnProperty('id')) return this.$toast({ title: '参数错误' }, () => {
				uni.navigateBack()
			})
			const { id } = ev
			this.initData(id)
			this.inPage = true
			this.id = id
			if (ev.hasOwnProperty('type')) {
				const { type } = ev
				this.joinType = type
			}
		},
		computed: {
			endTimeStr() {
				const { endValue } = this
				const minutes = Math.floor(endValue / 1000 / 60)
				const seconds = Math.ceil(endValue / 1000 % 60)
				return `请在${this.$patchZero(minutes)}分钟${this.$patchZero(seconds)}秒内完成支付`
			},
		},
		methods: {
			clearTimeout() {
				if (!timerID) return
				clearTimeout(timerID)
				timerID = null
			},
			confirmOrder() {
				uni.showModal({
					title: '温馨提示',
					content: `您确定将订单状态设置为已完成吗?`,
					success: async ev => {
						if (ev.cancel) return
						const { id } = this
						const resp = await this.$request({
							url: "/Order/confirmOrder",
							data: { id },
						})
						const { code, msg } = resp
						this.$toast({ title: msg })
						if (code < 1) return
						this.initData(id)
						uni.setStorageSync(UPDATE_ORDER_FLAG, true)
					}
				})
			},
			popupHandle(value) {
				this.showPopup = value
			},
			async confirmCancel(order_id) {
				const resp = await this.$request({
					url: "/Order/cancelOrder",
					data: { order_id },
				})
				const { code, msg } = resp
				this.$toast({ title: msg }, () => {
					if (code !== 1) return
					if (this.joinType === 'confirm') {
						uni.redirectTo({
							url: '/pages-bundle/order/index?active=0'
						})
						return
					}
					uni.$emit('updateOrder', true)
					uni.navigateBack()
				})
			},
			cancelOrder() {
				uni.showModal({
					title: '温馨提示',
					content: '您确定要取消订单吗?',
					success: ev => {
						if (ev.cancel) return
						return this.confirmCancel(this.id)
					}
				})
			},
			async confirmClose(order_id) {
				const resp = await this.$request({
					url: "/pay/refund",
					data: { order_id, refund_remake: '' },
				})
				const { code, msg } = resp
				const title = code === 1 ? '申请成功' : msg
				this.$toast({ title: msg }, () => {
					if (code !== 1) return
					uni.$emit('updateOrder', true)
					uni.navigateBack()
				})
			},
			closeOrder() {
				uni.showModal({
					title: '提示',
					content: '您确定要申请退款吗?',
					success: ev => {
						if (ev.cancel) return
						return this.confirmClose(this.id)
					}
				})
			},
			mpWxPayOrder(id) {
				uni.showLoading({
					title: '正在提交',
					mask: true
				})
				wxPerPay(id, {
					success: opt => {
						mpWxPay(opt, id, {
							success: () => {
								uni.hideLoading()
								this.$toast({ title: '支付成功' })
								this.initData(this.id)
							},
							fail: () => {
								uni.hideLoading()
								this.$toast({ title: '支付失败' })
							}
						})
					},
					fail: () => {
						uni.hideLoading()
						this.$toast({ title: "提交失败" })
					}
				})
			},
			async payOrder() {
				// #ifdef MP-WEIXIN
				return this.mpWxPayOrder(this.id)
				// #endif
			},
			endTimeConfirm() {
				uni.showModal({
					title: '订单提示',
					content: '订单支付超时已自动取消,请重新下单！',
					showCancel: false,
					success: ev => {
						uni.navigateBack()
					}
				})
			},
			dispatchTime() {
				if (this.endValue <= 0) return this.clearTimeout()
				timerID = setTimeout(() => {
					this.endValue -= 1000
					if (this.endValue <= 0) {
						this.endValue = 0
						return this.endTimeConfirm()
					}
					this.dispatchTime()
				}, 1000)
			},
			createInterval(createTime) {
				const startDate = new Date(createTime)
				const startValue = startDate.getTime()
				const { orderMaxTime } = this
				const endValue = startValue + (orderMaxTime * 1000 * 60)
				const end = endValue - Date.now()
				if (end <= 0) return this.endTimeConfirm()
				this.endValue = end
				this.dispatchTime(endValue)
			},
			initHotelInfo(list) {
				if (!list || !list.length) return
				const result = []
				list.forEach(item => {
					const { hotel_id, type_name, value, type_id, hotel_name: hotelName } = item
					const target = result.find(item => item.id === hotel_id)
					const typeItem = {
						name: type_name,
						number: value,
						typeId: type_id
					}
					if (!target) return result.push({
						id: hotel_id,
						hotelName,
						children: [typeItem]
					})
					target.children.push(typeItem)
				})
				console.log(result, 'result');
				this.hotelData = result
			},
			formatDate(timestamp) {
				const date = new Date(timestamp)
				const [year, month, day, hour, minute, seconds] = [date.getFullYear(), date.getMonth() + 1, date.getDate(),
					date.getHours(), date.getMinutes(), date.getSeconds()
				]
				return `${year}-${this.$patchZero(month)}-${this.$patchZero(day)} ${this.$patchZero(hour)}:${this.$patchZero(minute)}:${this.$patchZero(seconds)}`
			},
			async initData(id) {
				const resp = await this.$request({
					url: "/Order/detailsOrder",
					data: { id },
				})
				const { code, data, msg } = resp
				if (code !== 1) return this.$toast({ title: msg }, () => {
					uni.navigateBack()
				})
				const {
					status,
					create_time,
					order_no,
					pay_time,
					linkman_name,
					linkman_remake,
					linkman_tel,
					old_num,
					adult_num,
					child_num,
					lineInfo,
					hotelInfo
				} = data
				this.status = status
				this.createTime = create_time
				this.orderNo = order_no
				this.payTime = this.formatDate(pay_time * 1000)
				this.userName = linkman_name
				this.userPhone = linkman_tel
				this.userRemark = linkman_remake
				this.oldNum = old_num
				this.adultNum = adult_num
				this.childNum = child_num
				const { line_name, introductory, cover_image } = lineInfo
				this.lineImage = cover_image
				this.lineName = line_name
				this.lineDesc = introductory
				this.initHotelInfo(hotelInfo)
				if (status * 1 === 1) {
					this.createInterval(create_time)
				} else {
					this.clearTimeout()
				}
				this.loading = false
			}
		},
		data() {
			return {
				id: '',
				loading: false,
				status: 1,
				orderMaxTime: 30, //未付款10分钟
				endValue: 0,
				createTime: '',
				orderNo: '',
				payTime: '',
				userName: '',
				userPhone: '',
				userRemark: '',
				oldNum: 0,
				adultNum: 0,
				childNum: 0,
				lineName: '',
				lineDesc: '',
				hotelData: [],
				joinType: '',
				showPopup: false,
				lineImage: '',
				inPage: false,
			};
		},
		components: { ServicePopup },
	}
</script>

<style lang="scss" scoped>
	.order-detail-container {
		padding: 32rpx 32rpx env(safe-area-inset-bottom);

		.footer-wrap {
			display: flex;
			justify-content: flex-end;
			margin-top: 24rpx;

			.btn-item {
				width: 188rpx;
				height: 58rpx;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				border: 2rpx solid rgba(0, 0, 0, 0.26);
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 20rpx;
				color: rgba(0, 0, 0, 0.9);

				&.service {
					margin-right: 24rpx;
				}

				&.confirm {
					background: linear-gradient(135deg, #8BDCFF 0%, #E4FF68 100%);
					margin-left: 24rpx;
					color: rgba(0, 0, 0, 0.9);
				}
			}
		}

		.buy-info-wrap {
			padding: 24rpx;
			box-sizing: border-box;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			margin-top: 24rpx;

			.info-list-wrap {
				.info-item {
					display: flex;
					align-items: center;
					margin-bottom: 16rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.info-value {
						height: 40rpx;
						font-size: 24rpx;
						color: rgba(0, 0, 0, 0.9);
						line-height: 40rpx;
						margin-left: 40rpx;
						word-break: break-all;
					}

					.info-label {
						height: 40rpx;
						font-size: 24rpx;
						color: rgba(0, 0, 0, 0.6);
						line-height: 40rpx;
					}
				}
			}

			.info-line {
				margin: 16rpx 0;
				background-color: #EEEEEE;
				width: 100%;
				height: 1px;
			}

			.header {
				height: 44rpx;
				font-size: 28rpx;
				color: rgba(0, 0, 0, 0.9);
				line-height: 44rpx;
				font-weight: bold;
			}
		}

		.order-info-wrap {
			margin-top: 24rpx;
			padding: 24rpx;
			background-color: #FFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;

			.line {
				background-color: #E5E6EB;
				width: 100%;
				height: 1px;
				margin: 16rpx 0;
			}

			.tip-list {
				.tip-item {
					font-size: 24rpx;
					color: #F38224;
					line-height: 40rpx;
					word-break: break-all;
					margin-bottom: 4rpx;

					&:last-child {
						margin-bottom: 0;
					}
				}
			}

			.order-info {
				display: flex;


				.text-desc {
					flex: 1;
					margin-right: 16rpx;

					.order-desc-list {
						margin-top: 4rpx;

						.order-desc-item {
							font-size: 24rpx;
							color: rgba(0, 0, 0, 0.6);
							line-height: 40rpx;
							margin-bottom: 4rpx;

							.hotel-name-text {
								margin-right: 8rpx;
							}

							.hotel-type-item {
								margin-right: 4rpx;

								&:last-child {
									margin-right: 0;
								}
							}

							&:last-child {
								margin-bottom: 0;
							}
						}
					}

					.text-title {
						font-size: 30rpx;
						font-weight: bold;
						color: rgba(0, 0, 0, 0.9);
						line-height: 52rpx;
						word-break: break-all;
					}

				}

				.order-image {
					width: 176rpx;
					height: 176rpx;
					border-radius: 16rpx 16rpx 16rpx 16rpx;
					flex-shrink: 0;
					margin-left: auto;
					overflow: hidden;
				}
			}
		}

		.order-status-bar {
			display: flex;
			align-items: center;

			.title {
				height: 56rpx;
				font-size: 40rpx;
				color: rgba(0, 0, 0, 0.9);
				line-height: 56rpx;
				font-weight: bold;
			}

			.desc {
				height: 40rpx;
				font-size: 24rpx;
				color: rgba(0, 0, 0, 0.6);
				line-height: 40rpx;
				margin-left: 16rpx;
			}
		}
	}
</style>